/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.brain.core.view.util;

import com.brain.core.common.UtilCore;
import com.brain.core.configuracion.WebServletContextListener;
import com.brain.core.dto.ProductoDto;
import com.brain.core.manager.ProductoManager;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import org.apache.log4j.Logger;


/**
 *
 * @author Indra
 */
@FacesConverter("productoConvert")
public class ProductoConvert implements Converter {
    private static Logger logger = Logger.getLogger(ProductoConvert.class);
    

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String value) {        
        if (value==null || value.trim().equals("")) {           
            return null;
        } else {
            if(!UtilCore.isParsableToLong(value)){
                ProductoDto prod = new ProductoDto();
                prod.setId(-1l);
                return prod;
            }
            Long id = Long.valueOf(value);
            try {                
                ProductoManager manager = (ProductoManager) WebServletContextListener.getApplicationContext().getBean("productoManager");                              
                return manager.obtenerPorId(id);
            } catch (Exception exception) {
                logger.error(exception);
                return null;
            }
        }

    }

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object value) {
        if (value == null || value.equals("")) {
            return "";
        } else {
            return String.valueOf(((ProductoDto) value).getId());
        }
    }
}
